from sqlalchemy import Boolean, Column, Integer, String, ForeignKey, DateTime, event, text
from sqlalchemy.orm import relationship
from models.base import Base
from pydantic import BaseModel, Field
from typing import Optional
from typing import  List
from models.admin_menu_permission import admin_menu_permission
from models.permission import PermissionSchema
from datetime import datetime
from sqlalchemy.sql import func

class AdminMenu(Base):
    __tablename__ = 'admin_menus'

    id = Column(Integer, primary_key=True, autoincrement=True, comment='主键ID')
    parent_id = Column(Integer, ForeignKey('admin_menus.id'), nullable=True, comment='父菜单ID')
    selected = Column(String(50), nullable=True, comment='选中状态')
    type = Column(Integer, nullable=False, comment='菜单类型，1, 2 或 3')
    path = Column(String(255), nullable=False, comment='菜单路径，对应前端路由路径')
    title = Column(String(255), nullable=False, comment='菜单名称，显示在界面上的文本')
    params = Column(String(255), nullable=True, comment='附加参数，以JSON字符串形式存储')
    component = Column(String(255), nullable=True, comment='前端组件路径')
    redirect = Column(String(255), nullable=True, comment='重定向路径')
    icon = Column(String(255), nullable=True, comment='菜单图标，用于界面显示的图标类名')
    is_link = Column(Boolean, default=False, comment='是否外链')
    target = Column(String(50), nullable=True, default='_self', comment='链接打开方式')
    is_tabs = Column(Boolean, default=False, comment='是否标签页显示')
    is_cache = Column(Boolean, default=False, comment='是否缓存')
    is_breadcrumb = Column(Boolean, default=True, comment='是否显示面包屑')
    is_hidden = Column(Boolean, default=False, comment='是否隐藏')
    permission_id = Column(Integer, ForeignKey('permissions.id'), nullable=True, comment='权限ID')
    sort = Column(Integer, default=0, comment='排序')
    status = Column(Integer, nullable=False, comment='状态，1 或 2')
    deleted_at = Column(DateTime, comment='删除时间')
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), comment='更新时间')
    parent = relationship('AdminMenu', remote_side=[id])
    permissions = relationship(
        "Permission",
        secondary=admin_menu_permission,
        back_populates='menus'
    )
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

@event.listens_for(AdminMenu, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(AdminMenu, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

class AdminMenuSchema(BaseModel):
    id: int
    parent_id: Optional[int]
    selected: Optional[str]
    type: int
    path: str
    title: str
    params: Optional[str]
    component: Optional[str]
    redirect: Optional[str]
    icon: Optional[str]
    is_link: bool
    target: Optional[str]
    is_tabs: bool
    is_cache: bool
    is_breadcrumb: bool
    is_hidden: bool
    permission_id: Optional[int]
    sort: int
    status: int
    permissions: List[PermissionSchema]  # 添加权限字段
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }


# 在模型定义之后添加关系
AdminMenu.permission = relationship(
    "Permission",
    secondary=admin_menu_permission,
    back_populates='menus'
)

AdminMenu.role_menus = relationship('SysRoleMenu', back_populates='admin_menu')
